package com.itboye.qihang;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;


import android.net.http.SslError;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;


import android.view.View;
import android.view.ViewGroup;
import android.webkit.ClientCertRequest;

import android.webkit.JsPromptResult;
import android.webkit.PermissionRequest;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.itboye.qihang.consts.UserConst;
import com.itboye.qihang.util.ByAlert;
import com.itboye.qihang.util.GlideLoader;
import com.itboye.qihang.util.SPUtils;
import com.itboye.qihang.util.uploadmultipleimage.MultipartRequest;
import com.just.library.AgentWeb;
import com.just.library.AgentWebView;
import com.just.library.WrapperWebViewClient;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.itboye.qihang.MyApplication.api;


public class MainActivity extends AppCompatActivity {


    WebView webView;
//    String urls="http://hzzhongrui.travel.bbcmart.com/";
    String urls="http://fangapp.8raw.com/#/";
    ProgressBar myProgressBar;
    RelativeLayout rl;
    FrameLayout fram;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mains);
        webView= (WebView) findViewById(R.id.web);
        myProgressBar= (ProgressBar) findViewById(R.id.myProgressBar);
        fram= (FrameLayout) findViewById(R.id.fram);
        rl= (RelativeLayout) findViewById(R.id.rl);
//
//
        WebSettings webSettings = webView.getSettings();
//        webSettings.setPluginState(WebSettings.PluginState.valueOf(Controller.getInstance().getPreferences().getString(SyncStateContract.Constants.PREFERENCES_BROWSER_ENABLE_PLUGINS, WebSettings.PluginState.ON_DEMAND.toString())));
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);

        webSettings.setAppCacheEnabled(true); //缓存
        webSettings.setDomStorageEnabled(true);//开启DOM storage API功能
//        webSettings.supportMultipleWindows();
//        webSettings.setAllowContentAccess(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);
//        webSettings.setSavePassword(true);
//        webSettings.setSaveFormData(true);
        webSettings.setNeedInitialFocus(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);

        webView.loadUrl(urls);
        webView.setWebViewClient(new WebViewClient(){

//            @Override
//            public void onLoadResource(WebView view, String url) {
//                Log.d("=====LoadRes",url);
//                super.onLoadResource(view, url);
//            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Log.d("=====request",request.toString());


                return super.shouldOverrideUrlLoading(view,request);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

                handler.proceed();  //接受所有证书
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d("=====url",url);
                return super.shouldOverrideUrlLoading(view,url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
                Log.d("=====onReceivedCl",request.toString());
                super.onReceivedClientCertRequest(view, request);


            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                Log.d("=====onReceivedEr",request.toString());
                super.onReceivedError(view, request, error);

            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Log.d("=====onReceivedErUrl",failingUrl);
                super.onReceivedError(view, errorCode, description, failingUrl);

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.d("=====onPageStarted",url);
                super.onPageStarted(view, url, favicon);
            }


        });

        webView.setWebChromeClient(new WebChromeClient(){

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                Log.d("=====JsPrompt",url);
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }

            @Override
            public void onPermissionRequest(PermissionRequest request) {
                Log.d("=====onRequest",request.toString());
                super.onPermissionRequest(request);
            }


            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                myProgressBar.setProgress(newProgress);
                if (newProgress==100){
                    fram.setVisibility(View.GONE);
                    myProgressBar.setVisibility(View.GONE);
//                    wxShare();
                }else {
                    fram.setVisibility(View.VISIBLE);
                    myProgressBar.setVisibility(View.VISIBLE);
                }
            }
        });




    }

    private void wxShare(){

        //分享

        //初始化一个WXWebpageObject，填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl ="网页url";

//用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title ="网页标题 ";
        msg.description ="网页描述";
//                Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.drawable.send_music_thumb);
//                msg.thumbData =Util.bmpToByteArray(thumbBmp, true);

//构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
//                req.transaction = buildTransaction("webpage");
        req.message =msg;
//                req.scene =mTargetScene;
//                req.userOpenId = getOpenId();

//调用api接口，发送数据到微信
        api.sendReq(req);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
//                usericon_nicheng.setText("" + data.getStringExtra("nickname"));
            }  else if (requestCode == ImageSelector.IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
                List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
                String paths="";
                for (String path : pathList) {
                    Log.i("ImagePathList", path);
                    paths=pathList.get(0);
                }
                onImage(paths);
            }
        }
    }

    //6.0添加拍照的权限
    private static String[] PERMISSIONS_CAMERA_AND_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    public static boolean isCameraPermission(Activity context, int requestCode){
        if (Build.VERSION.SDK_INT >= 23) {
            int storagePermission = ActivityCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int cameraPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
            if (storagePermission != PackageManager.PERMISSION_GRANTED || cameraPermission!= PackageManager.PERMISSION_GRANTED ) {
                ActivityCompat.requestPermissions(context, PERMISSIONS_CAMERA_AND_STORAGE,
                        requestCode);
                return false;
            }
        }
        return true;
    }

    /**
     * 打开图库
     */
    private void pic() {
        isCameraPermission(this,1);
        ImageConfig imageConfig
                = new ImageConfig.Builder(new GlideLoader())
                .steepToolBarColor(getResources().getColor(R.color.blue))
                .titleBgColor(getResources().getColor(R.color.blue))
                .titleSubmitTextColor(getResources().getColor(R.color.white))
                .titleTextColor(getResources().getColor(R.color.white))
                // 开启单选   （默认为多选）
                .singleSelect()
                // 开启拍照功能 （默认关闭）
                .showCamera()
                // 已选择的图片路径
                // .pathList(path)
                // 拍照后存放的图片路径（默认 /temp/picture） （会自动创建）
                .filePath("/ImageSelector/Pictures")
                .build();
        ImageSelector.open(this, imageConfig);   // 开启图片选择器
    }


    /**
     * 上传图片
     * @param str 地址
     */
    private void onImage(String str){
        File files = new File(str);
        if (str == null) {
            Toast.makeText(this,"请上传相关图片",Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> params = new HashMap<String, String>();
//        params.put("uid",uid);
        params.put("type", "avatar");

        MultipartRequest multipartRequest = new MultipartRequest(
                UserConst.URL
                        + "/file/upload?client_id=by565fa4facdb191",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String arg0) {
                        Log.d("urlTime", arg0.toString());
                        allInfoFromJson(arg0.toString());
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
                // TODO Auto-generated method stub
                ByAlert.alert(arg0);
            }
        }, "image", files, params);
        MyApplication.addRequest(multipartRequest);

    }

    public void allInfoFromJson(String jsonStr) {
        try {
            JSONArray jsonArray = new JSONObject(jsonStr).getJSONArray("data");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                String busName = jsonObject.getString("id");
                Log.d("busLin", busName);
                ByAlert.alert("上传成功");
//                SPUtils.put(this, "", SPContants.AVATAR_URL, busName);
                initavatar();
//                Intent intent = new Intent(AVARTACTION);
//                sendBroadcast(intent);
//                try {
//                    closeProgressDialog();
//                } catch (Exception e) {
//                    // TODO: handle exception
//                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            ByAlert.alert("上传失败");
        }

    }


    /**
     *  修改头像
     */
    private void initavatar() {
//        String url = "" + SPUtils.get(this, null, SPContants.AVATAR_URL, "");
//        System.out.println(url);
//        if (!url.equals("")) {
//            if (url.startsWith("http:")) {
//                XImageLoader.load(url, usericon_im);
//            } else if (url.equals("0")) {
//                usericon_im.setImageResource(R.drawable.default_head);
//            } else {
//                XImageLoader.load(NetPublicConstant.IMAGE_URL + url,
//                        usericon_im);
//            }
//        } else {
//            usericon_im.setImageResource(R.drawable.default_head);
//        }

    }

}
